package logic

import (
	"context"
	"strings"
	"time"

	"mall/common/cryptx"
	"mall/common/errorx"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendCreateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendCreateUserLogic {
	return &BackendCreateUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendCreateUserLogic) BackendCreateUser(in *backend.CreateUserRequest) (*backend.CreateUserResponse, error) {
	if len(strings.TrimSpace(in.Username)) == 0 {
		return nil, errorx.Status(errorx.ERROR_USERNAME_REQUIRED, "")
	}

	_, count, err := l.svcCtx.BackendUser.GetList(l.ctx, model.M{
		model.BackendUserColumns.Username: in.Username,
	}, 0)
	if err != nil {
		return nil, err
	}

	if count > 0 {
		return nil, errorx.Status(errorx.ERROR_USERNAME_EXISTS, "")
	}

	password, err := cryptx.GenerateRandomHexString(6)
	if err != nil {
		return nil, errorx.Status(errorx.ERROR_GENERATE_PASSWORD_EXCEPTION, "")
	}

	salt, err := cryptx.GenerateRandomHexString(16)
	if err != nil {
		return nil, errorx.Status(errorx.ERROR_GENERATE_PASSWORD_EXCEPTION, "")
	}

	var user model.BackendUser
	user.Username = in.Username
	user.Password = cryptx.PasswordEncrypt(salt, password)
	user.Salt = salt
	user.Nickname = in.Nickname
	user.Name = in.Name
	user.Email = in.Email
	user.Mobile = in.Mobile
	user.Status = uint16(in.Status)
	user.DelStatus = uint16(in.Status)
	user.CreatedBy = uint64(in.CreatedBy)
	user.LastUpdatedBy = uint64(in.CreatedBy)
	user.CreatedAt = time.Now()
	user.UpdatedAt = time.Now()
	// user.DeptId       = uint16(in.DeptId)
	// user.RoleId       = uint16(in.RoleId)

	err = l.svcCtx.BackendUser.Insert(l.ctx, &user)
	if err != nil {
		return nil, err
	}

	return &backend.CreateUserResponse{
		Password: password,
	}, nil
}
